import { editPwd, outLogin } from '@/services/ant-design-pro/api';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useModel, history } from '@umijs/max';
import { Modal, message } from 'antd';
import React, { cloneElement, useCallback, useState } from 'react';
import { stringify } from 'querystring';

//用于点击a标签出现modal框
interface CreateFormProps {
  trigger?: JSX.Element;
  // onCancel?: () => void;
}
const PasswordEdit: React.FC<CreateFormProps> = (props) => {

  const { initialState } = useModel('@@initialState');
  const { currentUserInfo } = initialState || {};
  const { trigger } = props;
  const [messageApi, contextHolder] = message.useMessage();
  const [open, setOpen] = useState(false);

  const intl = useIntl();

  
  const onCancel = useCallback(() => {
    setOpen(false);
  }, []);

  const onOpen = useCallback(() => {
    setOpen(true);
  }, []);

  //修改了密码后必须退出重新登录
  const loginOut = async () => {
    await outLogin();
    // 清除用户信息
    localStorage.removeItem('userInfo');
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };

  const onFinish = useCallback(
    async (values?: any) => {
      if (values) {
        //这里的values没有key，所以需要加上，后端需要key才能update
        if (values.pwdfirst === values.pwdrepeat) {
          const pwdbody = { password: values.pwdfirst, loginname: currentUserInfo?.loginname }
          const msg = await editPwd(pwdbody);
          if (msg.status === 200) {
            onCancel();
            await loginOut();
            messageApi.success(msg.data);
          }
          else {
            messageApi.error(msg.data);
          }
        }
        else {
          messageApi.error('两次输入的密码不匹配!');
        }
      }
    },
    [onCancel],
  );
  return (
    <>
      {contextHolder}
      {trigger
        ? cloneElement(trigger, {
          onClick: onOpen,
        })
        : null}
      <Modal
        destroyOnClose
        title={intl.formatMessage({
          id: 'pages.editpassword.addForm.title',
          defaultMessage: '修改密码信息',
        })}
        width="400px"
        open={open}
        //不显示取消和确定
        footer={null}
        onCancel={onCancel}
      >
        <ProForm
          onFinish={onFinish} // Handle form submission here  
        >
          <ProFormText
            name="pwdfirst"
            label={intl.formatMessage({
              id: 'pages.editpassword.Form.description',
              defaultMessage: '请输入密码',
            })}
            width="md"
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.editpassword.Form.ruleName.description"
                    defaultMessage="请输入密码"
                  />
                ),
              },
            ]}
          />
          <ProFormText
            name="pwdrepeat"
            label={intl.formatMessage({
              id: 'pages.editpassword.Form.description',
              defaultMessage: '请再次输入密码',
            })}
            width="md"
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.editpassword.Form.ruleName.description"
                    defaultMessage="请再次输入密码"
                  />
                ),
              },
            ]}
          />
        </ProForm>
      </Modal>
    </>
  );
};

export default PasswordEdit;
